package com.lagou.biz.dao;

import com.lagou.annotation.Service;
import com.lagou.biz.pojo.Account;
import com.lagou.utils.ConnectionUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author tengfei wang
 * @version 1.0
 * @date Created in 2020/8/31
 */
@Service("accountDao")
public class AccountDaoImpl implements AccountDao {

    private ConnectionUtils connectionUtils = ConnectionUtils.getInstance();

    @Override
    public Account getAccountByCartId(String cardId) {
        String sql = "select * from account where card_id = ?";
        try {
            Connection connection = connectionUtils.getCurrentThreadConn();
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, cardId);

            ResultSet resultSet = preparedStatement.executeQuery();
            Account account = new Account();
            while (resultSet.next()) {
                account.setCardId(resultSet.getString("card_id"));
                account.setAccountName(resultSet.getString("account_name"));
                account.setMoney(resultSet.getInt("money"));
            }
            System.out.println(account);
            return account;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void updateAccount(Account account) {
        String sql = "update account set money = ? where card_id = ?";
        try {
            Connection connection = connectionUtils.getCurrentThreadConn();
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, account.getMoney());
            preparedStatement.setString(2, account.getCardId());
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
